// pages/albumDetail/albumDetail.js
var app = getApp();
const api = require("../../utils/api.js");
import Toast from '../../miniprogram_npm/@vant/weapp/toast/toast'
let col1H = 0;
let col2H = 0;
Page({
  onShareTimeline: function () {
    return {
      title: "智克艺术 - 赛事直播" + this.data.matchInfo.name,
      query: {
        id: this.data.albumid
      },
      imageUrl: this.data.matchInfo.logo
    }
  },
  /**
   * 页面的初始数据
   */
  data: {
    show: false,
    topNum: 0,
    scrollH: 0,
    imgWidth: 0,
    loadingCount: 0,
    images: [],
    currentImgHeight:"",
    col1: [],
    col2: [],
    dataList: [],
    buttons: [],
    // 控制选中button的样式
    curindex: 0,
    page: 1,
    page1: 1,
    main: true,
    son: false,
    showbtn: false, //返回顶部
    matchInfo: [], //赛事信息
  },
  // 选择中间的四个按钮
  handleSelect(e) {
    const that = this;
    switch (e.currentTarget.id) {
      case "1":
        if (that.data.matchInfo.is_ticket == 0) {
          wx.showToast({
            title: "暂未开通",
            icon: "none"
          })
          return
        }
        wx.navigateTo({
          url: `/test/pages/buyTicket/buyTicket?id=${this.data.albumid}`,
        })
        break;
      // case "2":
      //   if (that.data.matchInfo.is_sign == 0) {
      //     wx.showToast({
      //       title: "暂未开通",
      //       icon: "none"
      //     })
      //     return
      //   }
      // case "3":
      //   if (that.data.matchInfo.is_sign == 0) {
      //     wx.showToast({
      //       title: "暂未开通",
      //       icon: "none"
      //     })
      //     return
      //   }
      // case "4":
      //   if (that.data.matchInfo.is_sign == 0) {
      //     wx.showToast({
      //       title: "暂未开通",
      //       icon: "none"
      //     })
      //     return
      //   }
    }
  },
  // 监听滚动到底部事件
  scrollEnd(e) {
    console.log('滚动加载')
    const that = this;
    that.loadImages(that.data.id, that.data.page)
  },
  // 监听滚动高度
  scrollcount(e) {
    let height = e.detail.scrollTop
    if (height > 500) {
      this.setData({
        showbtn: true
      })
    } else {
      this.setData({
        showbtn: false
      })
    }
  },
  // 点击人脸识别
  checkface() {
    wx.navigateTo({
      url: '/pages/checkFace/checkFace?matchId=' + this.data.albumid,
    })
  },
  // 打开右侧搜索菜单
  chooseMenu() {
    this.setData({
      show: true
    })
  },
  // 加载图片失败
  errorimg(e) {
    console.log(e.detail)
  },
  // 点击主类目按钮切换显示并重新渲染子类目
  changeBtn(e) {
    const that = this
    let buttons = that.data.buttons
    let index = e.currentTarget.dataset.index
    // var page=that.data.page1
    that.setData({
      curindex: index
    })
    if (buttons[index].classic_children[0]) {
      var classic_level_id = buttons[index].id
    } else {
      var classic_id = buttons[index].classic_children[that.data.sonindex].id
    }
    console.log(classic_level_id, classic_id)
    var type = 1
    that.setData({
      show: false,
      type: 1,
      col1: [],
      col2: [],
      page: 1
    })
    var page = that.data.page
    that.loadImages(classic_level_id, page, type)
    return
    wx.request({
      url: app.globalData.host + 'competition/photo_search',
      data: {
        classic_level_id,
        classic_id,
        page
      },
      method: 'POST',
      success(res) {
        // that.onClose()
        let images = res.data.data;
        if (images == '') {
          Toast(res.data.msg)
          return
        } else {
          let baseId = "img-" + (+new Date());
          for (let i = 0; i < images.length; i++) {
            images[i].id = baseId + "-" + i + '-' + images[i].id;
          }
          var page = that.data.page
          page++
          that.setData({
            loadingCount: images.length,
            images: images,
            page,
            col1: [],
            col2: []
          });
        }
      }
    })
  },
  // 关闭侧边栏
  onClose() {
    this.setData({
      show: false
    })
  },
  // 进入图片预览界面
  preview(e) {
    let id = e.currentTarget.dataset.id
    wx.navigateTo({
      url: '/pages/downloadPic/downloadPic?id=' + id + '&compet_id=' + this.data.matchInfo.id,
    })
  },
  // 返回顶部
  goTop() {
    this.setData({
      topNum: 0
    });
  },
  // 获取图片
  loadImages(ids, page, type) {
    const that = this
    var type = type || that.data.type
    if (type == 1) {
      var classic_level_id = ids
    } else if (type == 2) {
      var classic_id = ids
    } else {
      // var id = ids
    }
    console.log('page' + page)
    var id = parseInt(that.data.albumid)
    wx.request({
      url: app.globalData.host + 'competition/photo_list',
      method: 'POST',
      data: {
        classic_level_id,
        classic_id,
        id,
        page
      },
      success(res) {
        let images = res.data.data;
        // if(images==''){
        //   Toast('暂无更多图片')
        //   return
        // }else{
        let baseId = "img-" + (+new Date());
        for (let i = 0; i < images.length; i++) {
          images[i].id = baseId + "-" + i + '-' + images[i].id;
          // }
          that.setData({
            loadingCount: images.length,
            images
            
          });
        }
        page++;
        that.setData({
          page
        })
      },
      fail(err) {
        console.log(err)
      }
    })

  },
  // 获取赛事信息
  getMatchDetail(id) {
    const that = this
    wx.request({
      url: app.globalData.host + 'Competition/competition',
      method: 'POST',
      data: {
        id
      },
      success(res) {
        let data = res.data.data
        that.setData({
          matchInfo: data
        })
      }
    })
  },
  // 获取侧边栏信息
  getMenuList(id) {
    const that = this
    wx.request({
      url: app.globalData.host + 'competition/classic',
      method: 'POST',
      data: {
        compet_id: id
      },
      success(res) {
        let data = res.data.data
        that.setData({
          buttons: data
        })
      }
    })
  },
  // 点击侧边栏二级分类重新请求图片
  chooseType(e) {
    let id = e.currentTarget.dataset.id
    let idx = e.currentTarget.dataset.idx

    console.log(id, idx)
    const that = this
    // let buttons = that.data.buttons
    // let index = e.currentTarget.dataset.index
    // this.loadImages(id,0)
    that.setData({
      id,
      show: false,
      sonindex: idx
    })
    var classic_id = id
    var type = 2
    console.log('子类目加载')
    that.setData({
      type: 2,
      col1: [],
      col2: [],
      page: 1
    })
    var page = that.data.page
    that.loadImages(classic_id, page, type)
    return
    var classic_id = id
    wx.request({
      url: app.globalData.host + 'competition/photo_search',
      data: {
        classic_id
      },
      method: 'POST',
      success(res) {
        that.onClose()
        let images = res.data.data;
        if (images == '') {
          Toast(res.data.msg)
          that.setData({
            images: images,
            col1: [],
            col2: []
          });
          return
        } else {
          let baseId = "img-" + (+new Date());
          for (let i = 0; i < images.length; i++) {
            images[i].id = baseId + "-" + i + '-' + images[i].id;
          }
          var page = that.data.page
          page++
          that.setData({
            loadingCount: images.length,
            images: images,
            page,
            col1: [],
            col2: []
          });
        }
      }
    })

  },
  // 处理图片
  onImageLoad: function (e) {
    const that = this
    let imageId = e.currentTarget.id;
    let oImgW = e.detail.width; //图片原始宽度
    let oImgH = e.detail.height; //图片原始高度
    let imgWidth = that.data.imgWidth; //图片设置的宽度
    let scale = imgWidth / oImgW; //比例计算
    let imgHeight = oImgH * scale; //自适应高度
    let images = that.data.images;
    /**
     * 新增开始
     */
    this.setData({
      currentImgHeight:imgHeight
    })
/**
 * 新增结束
 */
    let imageObj = null;
    for (let i = 0; i < images.length; i++) {
      let img = images[i];
      if (img.id === imageId) {
        imageObj = img;
        break;
      }
    }
    if(!imageObj)return;
    imageObj.height = imgHeight;
    let loadingCount = that.data.loadingCount - 1;
    let col1 = that.data.col1;
    let col2 = that.data.col2;
    if (col1H <= col2H) {
      col1H += imgHeight;
      col2.push(imageObj);
    } else {
      col2H += imgHeight;
      col1.push(imageObj);
    }
    let data = {
      loadingCount: loadingCount,
      col1: col1,
      col2: col2
    };
    if (!loadingCount) {
      data.images = [];
    }
    that.setData(data);
  },
  getOpenId() {
    wx.login({
      success: (res) => {
        //console.log(res)
        wx.request({
          url: app.globalData.host + `Wechat/get_user_info?code=${res.code}`,
          success: (req) => {
            var openid = req.data.data.openid
            app.globalData.openid = openid
            app.globalData.tmplIds = req.data.data.form_id;
            if (!wx.getStorageSync('type')) {
              api.fetchApi('Wechat/add_tourist', {
                openid
              }).then(res => {
                let token = res.token;
                wx.setStorageSync('token', token)
              })
            }
          }

        })
      },
      fail: (err) => {
        // console.log(err)
        wx.showToast({
          title: '登录失败',
          icon: 'none'
        })
      }
    })

  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.getOpenId()
    const that = this
    wx.getSystemInfo({
      success: (res) => {
        let ww = res.windowWidth;
        let wh = res.windowHeight;
        let imgWidth = ww * 0.48;
        let scrollH = wh;
        that.setData({
          scrollH: scrollH,
          imgWidth: imgWidth,
          url: options.url,
          albumid: options.id
        });
        that.loadImages(options.id, that.data.page);
        that.getMatchDetail(options.id)
        that.getMenuList(options.id)
      }
    })

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    console.log(123456789);
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})